//
//  ResetHeadViewController.m
//  Contacts
//
//  Created by 武 娇 on 14-8-27.
//  Copyright (c) 2014年 李 雷川. All rights reserved.
//

#import "ResetHeadViewController.h"
#import "MainViewController.h"
#import "Contact.h"
#import "JGProgressHUD.h"
#import "ImageExt.h"
#import "ServerInterface.h"
extern Contact *globalContact;
@interface ResetHeadViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate>

@end

@implementation ResetHeadViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    isUpload = NO;
    
    [self.headBtn setContentMode:UIViewContentModeScaleAspectFill];
    [self.headBtn setClipsToBounds:YES];
    [self.headBtn.layer setBorderColor:[UIColor whiteColor].CGColor];
    [self.headBtn.layer setBorderWidth:2.0];
    [self.headBtn.layer setCornerRadius:self.headBtn.frame.size.width/2.0];
    
    self.nameLabel.text = globalContact.name;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if (!isUpload) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"没有设置头像" message:@"请设置用户头像" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    return YES;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

}

- (IBAction)changeHead:(id)sender {
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"更换头像"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"拍照", @"从相册选择", nil];
    [sheet showFromRect:self.view.bounds inView:self.view animated:YES];
}


-(void)enterMainViewController{
    MainViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MainViewController"];
    [self.navigationController pushViewController:viewController animated:YES
     ];
}



#pragma mark
#pragma mark UIActionSheetDelegate

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate =self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:^{
        }];
        
    }
    else if (buttonIndex == 1) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate =self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:^{
        }];
        
        
    }
    
}
- (void)actionSheetCancel:(UIActionSheet *)actionSheet{
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    
}

#pragma mark
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //如果是 来自照相机的image，那么先保存
        UIImage* original_image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        UIImageWriteToSavedPhotosAlbum(original_image,nil,nil,
                                       nil);
    }
    
    //获得编辑过的图片
    UIImage* image = [info objectForKey: @"UIImagePickerControllerEditedImage"];
    [self uploadPhotoWithImage:image];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)uploadPhotoWithImage:(UIImage *)image{
    JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleExtraLight];
    HUD.textLabel.text = @"正在上传";
    [HUD showInView:self.view];
    
    image = [image scaleToSize:image size:CGSizeMake(image.size.width/3,image.size.height/3)];
    NSDictionary *paramDic = @{@"company_id":CompanyID,@"token":globalContact.token,@"user_id":@(globalContact.userID)};
    if (![[NSFileManager defaultManager] fileExistsAtPath:IMAGE_FORDER isDirectory:nil]) {
        [[NSFileManager defaultManager]createDirectoryAtPath:IMAGE_FORDER withIntermediateDirectories:YES attributes:nil error:nil];
    }
    double time = [[NSDate date]timeIntervalSince1970];
    NSString *imageName =[NSString stringWithFormat:@"%ld.png",(long)time];
    NSString *filePath =[IMAGE_FORDER stringByAppendingPathComponent:imageName];
    BOOL success = [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
    if (success) {
        [self.headBtn setImage:image forState:UIControlStateNormal];
        isUpload =  YES;
        [[NSFileManager defaultManager]removeItemAtPath:[IMAGE_FORDER stringByAppendingPathComponent:globalContact.headName] error:nil];
        [ServerInterface uploadHeadWithDic:paramDic withFileName:imageName withBlock:^(NSDictionary *headDic, NSError *error) {
            NSLog(@"headDic is:%@",headDic);
            if (error) {
                NSLog(@"error is:%@",error);
            }
            else{
                if ([[headDic valueForKeyPath:@"success"] boolValue]) {
                    globalContact.headName = imageName;
                    [Contact updateContact:globalContact];
                }
                else{
                }
            }
            [HUD dismissAfterDelay:1.0 animated:YES];
        }];
    }
    
}



@end
